from django.http import HttpResponse
from django.shortcuts import render_to_response
from polls.models import Poll, Choice
from django.http import Http404
from StartGroup.models import Group
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django import forms
from polls.models import PollForm, ChoiceForm
from django.http import QueryDict
from django.conf import settings
from django.core.paginator import Paginator, InvalidPage, EmptyPage


def index(request):
    latest_poll_list = Poll.objects.filter(group_web_address=request.session['group_web_address']).order_by('-pub_date')
    data = {}
    index_data = []
    for each in latest_poll_list:
        item = []
        votes = 0
        c = Choice.objects.filter(poll=each)
        for i in c:
                votes =  votes + i.votes 
                item.append((i.choice, votes))
        index_data.append((each, votes))
        data[each.poll_topic] = item
    paginator = Paginator(index_data, 5)
        
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        pages = paginator.page(page)
    except (EmptyPage, InvalidPage):
        pages = paginator.page(paginator.num_pages)
    return render_to_response('polls/index.html',
                { 'poll_data': data, 'poll_pages': pages })

def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/details.html', {'poll': p})


def results(request, poll_id):
    return HttpResponse("You're looking at the results of poll %s." % poll_id)

def vote(request, poll_id):
    p = Poll.objects.get(id=poll_id)
    c = Choice.objects.filter(poll=p)
    poll_topic = p.poll_topic
    choice = []
    for i in c:
        choice.append((i.choice, i))
    ChoiceFormClass = ChoiceForm(('poll', 'choice'))
    ChoiceFormClass.fields['votes'] = forms.CharField(label=poll_topic, widget=forms.widgets.RadioSelect(choices=choice))
    ChoiceFormClass.fields['votes'].required = True
        
    if request.POST:
        ChoiceFormClass = ChoiceForm(('poll', 'choice'), request.POST)
        ChoiceFormClass.fields['votes'] = forms.CharField(label=poll_topic, widget=forms.widgets.RadioSelect(choices=choice))
        ChoiceFormClass.fields['votes'].required = True
        bound = ChoiceFormClass.is_bound
        valid = ChoiceFormClass.choice_validation(bound)
        if valid:
            c = c.get(choice=request.POST.__getitem__('votes'))
            v = c.votes
            c.votes = v + 1
            c.save()
            return HttpResponseRedirect('../../')
        else:
            
            return render_to_response('polls/vote.html', {'vote_form': ChoiceFormClass }, context_instance=RequestContext(request))
    else:
        error_messages = 'Please Select an Option'
        return render_to_response('polls/vote.html', {'vote_form': ChoiceFormClass, 'error_messages': error_messages }, context_instance=RequestContext(request))

def add_poll(request):
    PollFormClass = PollForm(('group_web_address', 'pub_date', 'status'))
    PollFormClass.fields['poll_topic'] = forms.CharField(error_messages={'required': 'Please Enter the Poll Topic.'}, widget=forms.widgets.TextInput(attrs={'size':'25'}))
    PollFormClass.fields['poll_topic'].required = True
    PollFormClass.fields['choice_count'] = forms.CharField(widget=forms.widgets.HiddenInput(), initial=settings.NO_OF_CHOICES)
    choice_forms = []
    choice_object_list = []
    if request.POST:
        PollFormClass = PollForm(('group_web_address', 'pub_date','status'), data=request.POST)
        PollFormClass.fields['poll_topic'] = forms.CharField(error_messages={'required': 'Please Enter the Poll Topic.'}, widget=forms.widgets.TextInput(attrs={'size':'25'}))
        PollFormClass.fields['poll_topic'].required = True
        PollFormClass.fields['choice_count'] = forms.CharField(widget=forms.widgets.HiddenInput(), initial=settings.NO_OF_CHOICES)
        group = Group.objects.get(group_web_address=request.session['group_web_address'])
        poll_form_valid = PollFormClass.is_valid()
        if poll_form_valid:
            poll = PollFormClass.save(commit=False)
            poll.group_web_address = group
            poll.status = 0
        choice_list = request.POST.getlist('choice')
        qc = QueryDict('choice')
        qc = qc.copy()
        for i in range(int(request.POST['choice_count'])):
            qc.update({'choice' : choice_list[i]})
            ChoiceFormClass = ChoiceForm(('votes', 'poll'), qc)
            ChoiceFormClass.fields['choice'] = forms.CharField(error_messages={'required': 'Please Enter the choice %s.' % (i+1)}, widget=forms.widgets.TextInput(attrs={'size':'25'}))
            ChoiceFormClass.fields['choice'].required = True
                
            choice_form_valid = ChoiceFormClass.is_valid()   
            if choice_form_valid:
                choice = ChoiceFormClass.save(commit=False)
                choice_object_list.append(choice)
            choice_forms.append(ChoiceFormClass)
        
        if not poll_form_valid or not choice_form_valid:
            return render_to_response('polls/createpoll.html', {'poll_form': PollFormClass, 'choice_forms': choice_forms}, context_instance=RequestContext(request))    
        
        else:
            poll.save()
            for choice_instance in choice_object_list:
                choice_instance.poll = poll
                choice_instance.votes = 0
                choice_instance.save()
            return HttpResponseRedirect('../')
    else:
        for i in range(settings.NO_OF_CHOICES):
            ChoiceFormClass = ChoiceForm(('choice'))
            ChoiceFormClass.fields['choice'] = forms.CharField(error_messages={'required': 'Please Enter the choice %s.' % (i+1)}, widget=forms.widgets.TextInput(attrs={'size':'25'}))
            ChoiceFormClass.fields['choice'].required = True
            choice_forms.append(ChoiceFormClass)
        return render_to_response('polls/createpoll.html', {'poll_form': PollFormClass, 'choice_forms': choice_forms}, context_instance=RequestContext(request))